package cn.bingo.yunsj.mail;

import cn.bingo.yunsj.common.exception.EmException;
import cn.bingo.yunsj.common.exception.OwnException;
import cn.bingo.yunsj.mail.model.NewMailModel;
import cn.bingo.yunsj.mail.model.YmlProperties;
import cn.bingo.yunsj.mail.model.ImageModel;
import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 真正得邮件发送类
 */
public class MailSend {

    private String host;

    private String protocol;

    private String userName;

    private int port;

    private String password;

    private Properties props = null;

    private Session session = null;

    private MimeMessage message = null;

    private Transport trans = null;

    public MailSend() {
        YmlProperties ymlProperties = new YmlProperties();
        host = ymlProperties.getHost();
        protocol = ymlProperties.getProtocol();
        userName = ymlProperties.getUsername();
        port = ymlProperties.getPort();
        password = ymlProperties.getPassword();
    }

    private void init() {
        props = new Properties();
        // 设置邮件服务器主机名
        props.setProperty("spring.mail.host", host);
        // 发送邮件协议名称
        props.setProperty("spring.mail.protocol", protocol);
        // 设置环境信息
        session = Session.getInstance(props);

        message = new MimeMessage(session);
    }

    public void doSend(NewMailModel mailModel, List<ImageModel> imageModels, String html) throws MessagingException, UnsupportedEncodingException {

        // 初始化所需环境
        init();
        if(mailModel.getTitle() == null){
            message.setSubject("欢迎您的到来", "utf-8");
        }else {
            message.setSubject(mailModel.getTitle(), "utf-8");
        }
        //发送人
        message.setFrom(new InternetAddress(userName));
        //接收人
        message.setRecipients(Message.RecipientType.TO, getAddress(mailModel.getEmail()));
        if(!StringUtils.isEmpty(mailModel.getCcEmail())){
            //抄送人
            message.setRecipients(Message.RecipientType.CC, getAddress(mailModel.getCcEmail()));
        }
        if(!StringUtils.equals("全体员工",mailModel.getCcEmail())){
            //抄送人
            message.setRecipients(Message.RecipientType.CC, getAddress("zhoumingxin@bingosoft.net"));
        }
        //设置发送时间
        message.setSentDate(new Date());

        // 设置回复人(收件人回复此邮件时,默认收件人)
        message.setReplyTo(InternetAddress.parse("\"" + MimeUtility.encodeText("zmx") + "\" <zhoumingxin@bingosoft.net>"));
        // 设置优先级(1:紧急   3:普通    5:低)
//        message.setHeader("X-Priority", "3");
        // 要求阅读回执(收件人阅读邮件时会提示回复发件人,表明邮件已收到,并已阅读)
        message.setHeader("Disposition-Notification-To",userName);

        Multipart body = new MimeMultipart("related");// 附件传输格式

        // 邮件正文由html和图片构成
        MimeBodyPart htmlPart = new MimeBodyPart();
        body.addBodyPart(htmlPart);

        // 正文图片，支持多张图片
        imageModels.forEach(e -> {
            try {
                MimeBodyPart imgPart = new MimeBodyPart();
                imgPart.setDataHandler(new DataHandler(new FileDataSource(e.getImagePath())));
                imgPart.setContentID(e.getImageName());
                body.addBodyPart(imgPart);
            } catch (MessagingException e1) {
                e1.printStackTrace();
            }
        });

        // html邮件内容
        MimeMultipart htmlMultipart = new MimeMultipart("alternative");
        htmlPart.setContent(htmlMultipart);
        MimeBodyPart htmlContent = new MimeBodyPart();
        htmlContent.setContent(html
                , "text/html;charset=gbk");
        htmlMultipart.addBodyPart(htmlContent);

        message.setContent(body);
        message.saveChanges();

        trans = session.getTransport();
        trans.connect(host, port, userName, password);
        trans.sendMessage(message, message.getAllRecipients());
        destory();
    }

    //对收件人，抄送人进行切割
    private static InternetAddress[] getAddress(String email) throws AddressException {
        //不能使用string类型的类型，这样只能发送一个收件人
        List list = new ArrayList();
        //对输入的多个邮件进行逗号分割
        String[] median = email.split(",");
        for (int i = 0; i < median.length; i++) {
            list.add(new InternetAddress(median[i]));
        }
        //将list强制转化为数组
        return (InternetAddress[]) list.toArray(new InternetAddress[list.size()]);
    }

    private void destory() {
        if (trans != null) {
            try {
                trans.close();
            } catch (MessagingException e) {
                throw new OwnException(EmException.FILE_EXCPTION, e.getMessage());
            }
        }
    }
}
